source('/home/jc148322/scripts/libraries/cool_functions.r')
library(SDMTools)
timeline='Pre_decline'

wd= paste('/home/jc148322/frog_declines/SDM2/',timeline,'/models/',sep='') #your /models/ directory

species=list.files(wd)
clim.vars=paste('bioclim_',sprintf('%02i',c(1:19)),sep='')

for (spp in species) { cat(spp, '\n')
	
	spp.dir=paste(wd, spp, '/',sep=''); setwd(spp.dir)
	var.dirs=list.files(spp.dir)
	var.dirs=grep('bioclim',var.dirs,value=TRUE)
	var.dirs=var.dirs[rev(order(sapply(strsplit(var.dirs,'\\.'),length)))] #reorder by decreasing model complexity
	
	out=matrix(NA,nc=length(clim.vars),nr=length(var.dirs))
	colnames(out)=clim.vars
	i=0
	for (v in var.dirs){
	i=i+1
		var.dir=paste(spp.dir,v,'/',sep='');setwd(var.dir)
	
		results=read.csv('output/maxentResults.csv',as.is=TRUE)
		results=results[,grep('contribution',colnames(results))]
		colnames(results)=gsub('\\.contribution','',colnames(results))
		
		out[i,which(colnames(out) %in% colnames(results))]=as.matrix(results[1,])
	}
	setwd(spp.dir)
	write.csv(out,'climvar_contribution.csv',row.names=FALSE)
	
}
